import { Trade } from 'tradePublic/trade/types/trade';

/**
 * @function handleLogisticsData 处理请求回来的物流数据，用于展示
 * @return {}
 */
const handleLogisticsData = (requestData: Trade[]) : LogisticsInfoListWithMemo[] => {
    if (requestData && requestData.length < 1) {
        return [];
    }
    const handleData: LogisticsInfoListWithMemo[] = [];
    for (const value of requestData) {
        const ownMoreTrades = Reflect.has(value, 'trades');
        const orderInfo: OrderInfo = {
            tId: value.tid,
            payTime: value.pay_time,
            consignTime: value.consign_time,
        };
        const goodsImage: GoodsImage = { picPath: ownMoreTrades ? value.trades[0].pic_path : value.pic_path };
        const goodsInfo: GoodsInfo = { title: ownMoreTrades ? value.trades[0].title : value.title };
        const buyerInfo: CosumerInfo = {
            buyerNick: value.buyer_nick,
            receiverName: value.receiver_name,
            receiverMobile: value.receiver_mobile,
            receiverAddress: `${value.receiver_state} ${value.receiver_city}`,
        };
        const [info] = value.logisticsInfo;
        let logisticsInfo: LogisticsInfo;
        if (!info) {
            logisticsInfo = {
                sid: '暂无运单号',
                logisticsCompany: '暂无物流公司',
                logisticsInfo: [{ action: '', statusDesc: '暂无物流信息', statusTime: '' }],
            };
        } else {
            const traceStepInfo = info.trace_list.transit_step_info;
            logisticsInfo = {
                sid: info.out_sid,
                logisticsCompany: info.company_name,
                logisticsInfo: JSON.stringify(traceStepInfo[0]) === '{}'
                    ? [{ action: '', statusDesc: '暂无物流信息', statusTime: '' }]
                    : traceStepInfo.map((value: {action: string, status_desc: string, status_time: string}) => {
                        return { action: value.action, statusDesc: value.status_desc, statusTime: value.status_time };
                    }),
            };
        }

        const sellerMemo = ownMoreTrades ? value.trades.map(val => val.seller_memo) : [value.seller_memo];

        handleData.push({
            data: { goodsImage, orderInfo, goodsInfo, buyerInfo, logisticsInfo },
            memo: sellerMemo,
        });
    }

    return handleData;
};

export { handleLogisticsData };
